//
//  TransferPublishGoodsTableViewController.swift
//  甜言蜜语
//
//  Created by 王剑伟 on 16/7/18.
//  Copyright © 2016年 wl. All rights reserved.
//

import UIKit
import ActionSheetPicker_3_0
import SVProgressHUD
class TransferPublishGoodsTableViewController: UITableViewController, UICollectionViewDataSource, UICollectionViewDelegate, MTImagePickerControllerDelegate, ActionSheetCustomPickerDelegate {
    private var dataSource = [MTImagePickerModel]()//照片的数据源
    var collectionArr: [UIImage] = []
    
    @IBOutlet weak var footerView: UIView!
    @IBOutlet weak var collection: UICollectionView!
    @IBOutlet weak var titleTef: UITextField!
    @IBOutlet weak var body: UITextField!
    @IBOutlet weak var classity: UILabel!
    @IBOutlet weak var priceBuy: UITextField!
    @IBOutlet weak var priceSell: UITextField!
    @IBOutlet weak var newOldPlace: UILabel!
    @IBOutlet weak var newOld: UILabel!
    @IBOutlet weak var tel: UITextField!
    @IBOutlet weak var myAreaPlace: UILabel!
    @IBOutlet weak var myArea: UILabel!
    @IBOutlet weak var address: UITextField!
    @IBOutlet weak var photoImg: UIImageView!
    var modelList: loginInfo?{
        didSet{
            
        }
    }
    var msg: regiestInfo?
    
    var index1: NSInteger = 0 // 省下标
    var index2: NSInteger = 0 // 市下标
    var index3: NSInteger = 0 // 区下标
    
    var provinceArr: NSArray! //省
    var countryArr: NSArray! // 市
    var districtArr: NSArray! // 区
    var addressArr: NSArray! // 解析出来的最外层的数组
    
    override func viewDidLoad() {
        super.viewDidLoad()
        publicMethod.setHUDStyle()
        self.collection.hidden = true
        let cellNib = UINib(nibName: "FactoryCollCell", bundle: nil)
        self.collection.registerNib(cellNib, forCellWithReuseIdentifier: "FactoryCollCell")
        self.tableView.tableFooterView = footerView
        self.classity.text = "物品"
        self.calculateFirstData()
    }
    override func viewWillDisappear(animated: Bool) {
        SVProgressHUD.dismiss()
        super.viewWillDisappear(animated)
    }
    func calculateFirstData(){
        
        loadFirstData()
        let cityNameArr = NSMutableArray()
        
        print(addressArr.count)
        for cityName in (addressArr[index1].allValues.first) as! NSArray {
            
            let name1 = (cityName as! NSDictionary).allKeys.first
            cityNameArr.addObject(name1!)
        }
        // 组装对应省下面的市
        countryArr = cityNameArr
        
        districtArr = addressArr[index1].allObjects[0][index2].allValues[0] as! NSArray
        
    }
    func loadFirstData(){
        
        let path = NSBundle.mainBundle().pathForResource("address", ofType: "json")
        print(path)
        
        let data = NSData.init(contentsOfFile: path!)
        
        guard let myArr = try? NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) else {
            
            return
        }
        
        addressArr = myArr as! NSArray
        
        let firstName = NSMutableArray()
        for dict in addressArr {
            
            let name = (dict as! NSDictionary).allKeys.first
            firstName.addObject(name!)
        }
        provinceArr = firstName
        
        
    }
    //MARK: UIPickerViewDataSource Implementation
    
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 2
    }
    func pickerView(_pickerView: UIPickerView,
                    numberOfRowsInComponent component: Int) -> Int{
        switch (component)
        {
        case 0: return self.provinceArr.count;
        case 1: return self.countryArr.count;
        
        default:break;
        }
        return 0;
    }
    
    func pickerView(pickerView: UIPickerView,
                    titleForRow row: Int,
                                forComponent component: Int) -> String?{
        
        switch (component)
        {
        case 0: return self.provinceArr[row] as? String
        case 1: return self.countryArr[row] as? String
        
        default:break;
        }
        return nil;
    }
    func pickerView(pickerView: UIPickerView,
                    viewForRow row: Int,
                               forComponent component: Int,
                                            reusing view: UIView?) -> UIView{
        
        
        let label: UILabel! = UILabel()
        label!.font = UIFont.systemFontOfSize(14)
        
        var title = ""
        switch component {
        case 0:
            title = self.provinceArr[row] as! String
        case 1:
            title = self.countryArr[row] as! String
        
        default:
            break
        }
        
        label!.textAlignment = NSTextAlignment.Center
        label!.text = title
        return label!
        
    }
    func pickerView(pickerView: UIPickerView,
                    didSelectRow row: Int,
                                 inComponent component: Int){
        switch component {
        case 0:
            self.index1 = row
            self.index2 = 0
           
            //            [self calculateData];
            // 滚动的时候都要进行一次数组的刷新
            self.calculateFirstData()
            pickerView.reloadComponent(1)
            pickerView.selectRow(0, inComponent: 1, animated: true)
            
        case 1:
            self.index2 = row
          
        default:
            break
        }
        
    }
    //MARK:点击完成的按钮时执行
    func actionSheetPickerDidSucceed(actionSheetPicker: AbstractActionSheetPicker!, origin: AnyObject!) {
        var detailAddress = String()
        if self.index1 < self.provinceArr.count {
            let firstAddress = self.provinceArr[self.index1]
            detailAddress += firstAddress as! String
        }
        if self.index2 < self.countryArr.count {
            let secondAddress = self.countryArr[self.index2]
            detailAddress += secondAddress as! String
        }
        
        // 此界面显示
        print(detailAddress)
        self.myArea.text = detailAddress
        self.myAreaPlace.alpha = 0
    }
    

    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if(cell.respondsToSelector(Selector("setSeparatorInset:"))) {
            cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
        }
        if(cell.respondsToSelector(Selector("setLayoutMargins:"))) {
            cell.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0)
        }
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        
        if indexPath.row == 0{
            self.btnPickTouch()
        }
        if indexPath.row == 3{
            self.titleTef.resignFirstResponder()
            self.body.resignFirstResponder()
            self.priceBuy.resignFirstResponder()
            self.priceSell.resignFirstResponder()
            self.tel.resignFirstResponder()
            self.address.resignFirstResponder()
            

            
        }
        if indexPath.row == 6{
            self.titleTef.resignFirstResponder()
            self.body.resignFirstResponder()
            self.priceBuy.resignFirstResponder()
            self.priceSell.resignFirstResponder()
            self.tel.resignFirstResponder()
            self.address.resignFirstResponder()
            
            ActionSheetMultipleStringPicker.showPickerWithTitle("新旧程度", rows:[["9成新", "8成新", "7成新"]],initialSelection: [1,1], doneBlock: {
                picker, values, indexes in
                let obj = (indexes as! NSArray)[0] as! String
                self.newOldPlace.alpha = 0
                self.newOld.text = obj
                return
                }, cancelBlock: { ActionMultipleStringCancelBlock in return }, origin: self.view)
        }
        if indexPath.row == 8{
            self.titleTef.resignFirstResponder()
            self.body.resignFirstResponder()
            self.priceBuy.resignFirstResponder()
            self.priceSell.resignFirstResponder()
            self.tel.resignFirstResponder()
            self.address.resignFirstResponder()
            
            ActionSheetCustomPicker.showPickerWithTitle("请选择位置区域", delegate: self, showCancelButton: true, origin: self.view, initialSelections: [index1, index2])

        }
    }
    
    
    func btnPickTouch() {
        
        var mediaTypes = [MTImagePickerMediaType]()
        let source = MTImagePickerSource.Photos
        mediaTypes.append(MTImagePickerMediaType.Photo)
        let vc = MTImagePickerController.instance
        vc.mediaTypes = mediaTypes
        vc.source = source
        vc.delegate = self
        vc.maxCount = 6
        let nc = UINavigationController(rootViewController: vc)
        self.presentViewController(nc, animated: true, completion: nil)

    }
    
    //选取照片相关
    @available(iOS 8.0, *)
    func imagePickerController(picker: MTImagePickerController, didFinishPickingWithPhotosModels models: [MTImagePickerPhotosModel]) {
        self.dataSource = models
        if self.dataSource.count > 0{
            self.photoImg.hidden = true
            self.collection.hidden = false
            self.collection.dataSource = self
            self.collection.delegate = self
            self.collection.reloadData()
        }

    }
    
    func imagePickerController(picker: MTImagePickerController, didFinishPickingWithAssetsModels models: [MTImagePickerAssetsModel]) {
        
        self.dataSource = models
        if self.dataSource.count > 0{
            self.photoImg.hidden = true
            self.collection.hidden = false
            self.collection.dataSource = self
            self.collection.delegate = self
            self.collection.reloadData()
        }
        
        
    }
    
    
    //MARK:UICollectionViewDataSource
    //每一组有多少个cell
    func collectionView(collectionView:UICollectionView,numberOfItemsInSection section: Int) -> Int{
        
        if self.dataSource.count == 0{
            return 0
        }else{
            return (self.dataSource.count)
        }
        
        
    }
    //设置每组的cell的边界
    func collectionView(collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,insetForSectionAtIndex section: Int) -> UIEdgeInsets{
        
        return UIEdgeInsetsMake(10, 10, 10, 10)//上左下右
    }
    //最小行间距
    func collectionView(collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat{
        return 10
    }
    //最小列间距
    func collectionView(collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat{
        return 10
    }
    //设定全局的Cell尺寸
    func collectionView(collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{
        
        return CGSizeMake(SCREEN_WIDTH/3-20,50)
        
    }
    //cell上显示的信息
    func collectionView(collectionView: UICollectionView,cellForItemAtIndexPath indexPath: NSIndexPath) ->UICollectionViewCell{
        
        let cell = self.collection.dequeueReusableCellWithReuseIdentifier("FactoryCollCell", forIndexPath: indexPath) as! FactoryCollCell
        let model = self.dataSource[indexPath.row]
        
        cell.iv.image = model.getThumbImage()
        
      
        
        collectionArr.append(model.getThumbImage()!)
        
        return cell
        
    }
    @IBAction func publishGoodsTransfer(){
        if self.titleTef.text == ""{
            SVProgressHUD.showErrorWithStatus("请输入标题")
           
            return
        }
        if self.body.text == ""{
            SVProgressHUD.showErrorWithStatus("请输入描述文字")
           
            return
        }
        if self.classity.text == ""{
            SVProgressHUD.showErrorWithStatus("请选择分类")
          
            return
        }
        if self.priceBuy.text == ""{
            SVProgressHUD.showErrorWithStatus("请输入买入价格")
           
            return
        }
        if self.priceSell.text == ""{
            SVProgressHUD.showErrorWithStatus("请输入想卖多少")
            
            return
        }
        if self.newOld.text == ""{
            SVProgressHUD.showErrorWithStatus("请选择新旧程度")
           
            return
        }
        if self.tel.text == ""{
            SVProgressHUD.showErrorWithStatus("请输入电话")
            
            return
        }
        if self.myArea.text == ""{
            SVProgressHUD.showErrorWithStatus("请选择我的位置")
           
            return
        }
        if self.address.text == ""{
            SVProgressHUD.showErrorWithStatus("请输入详细地址")
          
            return
        }else{
            self.compleInfo()
        }

    }
    //MARK:networking
    func compleInfo(){
        SVProgressHUD.showWithStatus("正在加载...")
        let param = ["name": self.titleTef.text!, "body": self.body.text!, "type":"物品", "treasuretype" :self.classity.text!, "buyprice": self.priceBuy.text!, "price": self.priceSell.text!, "newold": self.newOld.text!, "tel": self.tel.text!, "area": self.myArea.text!, "address": self.address.text!]
        DataTool.publicTransferMessage(param, imgArr: self.collectionArr, completionHandler: {(newModel) in
            guard let newDataes = newModel else {
                return
            }
            SVProgressHUD.dismiss()
            print(newDataes)
            self.msg = newDataes
            SVProgressHUD.showSuccessWithStatus(self.msg?.msg)
           
            self.navigationController?.popToRootViewControllerAnimated(true)
        })

    }

}
